package com.mingyuan.user.hander;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mingyuan.student.entitys.User;
import com.mingyuan.user.service.UserService;

@RequestMapping("user")
@Controller
public class UserControcller {
	
	@Autowired
	private UserService userService;
	@RequestMapping("login.do")
	public String userLogin(@RequestParam("password") String password, @RequestParam("username") String username) {

		if (username != null && password != null) {
			Subject currentUser = SecurityUtils.getSubject();

			if (!currentUser.isAuthenticated()) {
				// 把用户名和密码封装为 UsernamePasswordToken 对象
				UsernamePasswordToken token = new UsernamePasswordToken(username, password);
				// rememberme
				token.setRememberMe(true);
				try {
					System.out.println("1. " + token.hashCode());
					// 执行登录.
					currentUser.login(token);
				}
				// ... catch more exceptions here (maybe custom ones specific to your
				// application?
				// 所有认证时异常的父类.
				catch (AuthenticationException ae) {
					// unexpected condition? error?
					System.out.println("登录失败: " + ae.getMessage());
				}
			}
		}
		return "index";
	}
	@RequestMapping("reg.do")
	public String userReg(User user) {
		System.out.println(user);
		user.setCreateTime(new Date());
		String hashAlgorithmName = "MD5";
		Object credentials = user.getPassword();
		Object salt = ByteSource.Util.bytes(user.getUserName());;
		int hashIterations = 1024;		
		Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
		System.out.println(result);
		user.setPassword(result.toString());
		if(userService.addUser(user)==1) {
			return "redirect:/regsuccess.html";
		};
		return "error";
	}

}
